package com.societyGames.flashForms
{
	import flash.display.DisplayObject;
	import flash.events.Event;

	public class CenterScaleContainer extends SingleChildContainer
	{
		private var _desiredWidth:Number;
		private var _desiredHeight:Number;
		
		public override function set width(value:Number):void
		{	
			this._desiredWidth = value;
			recalculate();
		}
		
		public override function set height(value:Number):void
		{	
			this._desiredHeight = value;
			recalculate();
		}
		
		protected override function childSizeChangedHandler(event:Event):void
		{
			recalculate();
		}
		
		private function recalculate():void
		{
			if (this._child != null)
			{
				this._child.scaleX = 1;
				this._child.scaleY = 1;
				var scale:Number;
				if (this.child.width > this._desiredWidth || this.child.height > this._desiredHeight)
				{
					scale = Math.min(
						this._desiredWidth / this._child.width,
						this._desiredHeight / this._child.height 
					);
				}
				else
				{
					scale = 1;
				}
				this._child.scaleX = scale;
				this._child.scaleY = scale;
				this._child.x = (this._desiredWidth - this._child.width) / 2;
				this._child.y = (this._desiredHeight - this._child.height) / 2;
			}
		}
	}
}